//
//  PartsPriceController.m
//  Ghac 4S
//
//  Created by apple on 11-8-27.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#import "Global.h"
#import "PartsPriceController.h"
#import "DataFactory.h"
#import "KXML.h"
#import "KXPath.h"
#import "KXMLNode.h"
#import "MyPartsTableCell.h"
#import "MyPickerViewController.h"
#import "MySearchBarController.h"
#import "pinyin.h"

@interface PartsPriceController(private)
-(void) reloadDataWithPredictWords:(NSString*)predict;
-(void) reloadDataWithCartype:(NSString*)cartype;
-(void) searchBarReturn:(NSNotification*)sender;
@end



@implementation PartsPriceController
@synthesize tableView;
@synthesize cartypeBtn;
@synthesize carinfoLabel;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        // Custom initialization
        [self setTitle:@"parts price"];
        m_pickerViewController = [[MyPickerViewController alloc] init];
        m_predictString = nil;
        m_defaultValue = [NSUserDefaults standardUserDefaults];
    }
    return self;
}
- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
//-(void)viewDataWithPredictString:(NSString *)predictStr
//{
//    KXPath* path = [[KXPath alloc] initWithString:@"data" predicate:predictStr];
//    if ([m_dataList retainCount]) [m_dataList release];
//    m_dataList = [[m_xml arrayByXPath:path] retain];
//    [path release];
//    
//}
#pragma mark - View lifecycle
-(UIButton *)leftBottomBtn
{
    return nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    DataFactory* datafactory = [DataFactory sharedDataFactory];
    id dataProvide = [datafactory produceProviderWithDelegate:self];
    if (dataProvide == Nil)
    {
        NSLog(@"error1");
        return;
    }
    [datafactory askDatas:self.title];
    
    
    
    
    MySearchBarController* searchBarController = [[MySearchBarController alloc] init];
    CGRect mainframe = self.view.frame;
    CGRect barframe = searchBarController.view.frame;
    barframe.origin.y = mainframe.size.height - barframe.size.height;
    [searchBarController setViewFrame:barframe];
    [self.view addSubview:searchBarController.view];
//    searchBarController.targetView = searchBarController.view;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchBarReturn:) name:UITextFieldTextDidEndEditingNotification object:searchBarController.textfield];
    m_searchBarController = searchBarController;

}
-(void)onData:(id)sender
{
    m_xml = [[KXML alloc] initWithData:sender];
    KXPath* path = [[KXPath alloc] initWithString:@"data" predicate:Nil];
    [path release];
    NSArray* cartyleList = [Global cartypeList];
    NSString* cartype = [m_defaultValue objectForKey:GLOBAL_CARTYPE];
    [cartypeBtn setTitle:cartype forState:UIControlStateNormal];
    NSInteger index = [cartyleList indexOfObject:cartype];
    [self.carinfoLabel setText:[[Global carInfoList] objectAtIndex:index]];
    m_cartypeIndex = index;
    [self reloadDataWithCartype:[cartyleList objectAtIndex:m_cartypeIndex]];
}
-(void)searchBarReturn:(NSNotification*)sender
{
    UITextField* textfield = (UITextField*)[sender object];
    NSString* cartype = [[Global cartypeList] objectAtIndex:m_cartypeIndex];
    NSString* text = [textfield.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* predictwords;
    if(text.length == 0)
    {
        predictwords = [NSString stringWithFormat:@"model == '%@'", cartype];
    }
    else
    {
        predictwords = [NSString stringWithFormat:@"model == '%@' && name LIKE[cd] '*%@*'", cartype, text];
    }
    
    [self reloadDataWithPredictWords:predictwords];
    
}
-(void)reloadDataWithCartype:(NSString *)cartype
{
    NSString* predictwords = [NSString stringWithFormat:@"model == '%@'", cartype];
    [self reloadDataWithPredictWords:predictwords];
}
-(void)reloadDataWithPredictWords:(NSString *)predict
{
    KXPath* path = [[KXPath alloc] initWithString:@"data" predicate:predict];
    NSArray* list = [m_xml arrayByXPath:path];
    
    KRELEASE(m_dataDic);
    KRELEASE(m_lastSelectedIndexPath);
    m_dataDic = [[NSMutableDictionary alloc] init];
    
    for (NSInteger i = 0 ; i < list.count; i++)
    {
        KXMLNode* node = [list objectAtIndex:i];
        NSString* str = [node valueForKeyPath:@"name.__nodeValue__"];
        NSString* letter = [NSString stringWithFormat:@"%c", pinyinFirstLetter([str characterAtIndex:0])];
        letter = [letter uppercaseString];
        
        NSMutableArray* sectionObjectList = [m_dataDic objectForKey:letter];
        if (sectionObjectList == nil)
        {
            sectionObjectList = [NSMutableArray array];
            [m_dataDic setObject:sectionObjectList forKey:letter];
        }
        [sectionObjectList addObject:node];
        
    }
    [self.tableView reloadData];
    [path release];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSMutableArray* firstLetterList = [NSMutableArray arrayWithArray:[m_dataDic allKeys]];
    [firstLetterList simpleSort:YES];
    return [firstLetterList objectAtIndex:section];
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray* firstLetterList = [NSMutableArray arrayWithArray:[m_dataDic allKeys]];
    [firstLetterList simpleSort:YES];
    return firstLetterList;
}
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
//{
//    
//}
-(void)onError:(id)sender
{
    NSLog(@"onerror");
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidEndEditingNotification object:m_searchBarController.textfield];
    KRELEASE(m_searchBarController);
    self.view = nil;
    self.tableView = nil;
    self.cartypeBtn = nil;
    self.carinfoLabel = nil;
    [self.tabBarController release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyPartsTableCell* cell = (MyPartsTableCell*)[self.tableView dequeueReusableCellWithIdentifier:@"demo"];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MyPartsTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    NSMutableArray* firstLetterList = [NSMutableArray arrayWithArray:[m_dataDic allKeys]];
    [firstLetterList simpleSort:YES];
    NSArray* list = [m_dataDic objectForKey:[firstLetterList objectAtIndex:indexPath.section]];
    
    if (list == Nil) return cell;
    KXMLNode* node = [list objectAtIndex:indexPath.row];
    cell.titleLabelOnPreview.text = [node valueForKeyPath:@"name.__nodeValue__"];
    [cell.priceLableOnPreview setText:[NSString stringWithFormat:@"%@", [node valueForKeyPath:@"price.__nodeValue__"]]];
    [cell.infoOnDetail setText:[node valueForKeyPath:@"name.__nodeValue__"]];
    [cell.priceLableOnDetail setText:[NSString stringWithFormat:@"指导价：%@", [node valueForKeyPath:@"price.__nodeValue__"]]];
    CGRect rect = cell.frame;
    
    if (m_lastSelectedIndexPath != nil && [indexPath isEqual:m_lastSelectedIndexPath])
    {
        rect.size.height = 140;
        [cell showDetail];
    }
    else
    {
        rect.size.height = 35;
        [cell showPreview];
    }
    [cell setFrame:rect];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (m_lastSelectedIndexPath == nil || ![m_lastSelectedIndexPath isEqual:indexPath])
    {
        NSArray* indexList = [NSArray arrayWithObjects:indexPath, m_lastSelectedIndexPath, nil];
        KRELEASE(m_lastSelectedIndexPath);
        m_lastSelectedIndexPath = [indexPath retain];
        [self.tableView reloadRowsAtIndexPaths:indexList withRowAnimation:UITableViewRowAnimationLeft];
    }    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSMutableArray* firstLetterList = [NSMutableArray arrayWithArray:[m_dataDic allKeys]];
    return firstLetterList.count;
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSMutableArray* firstLetterList = [NSMutableArray arrayWithArray:[m_dataDic allKeys]];
    [firstLetterList simpleSort:YES];
    NSArray* list = [m_dataDic objectForKey:[firstLetterList objectAtIndex:section]];
    return list.count;
}
-(void)cartypeBtnClick:(id)sender
{
    if (m_pickerViewController == nil)
    {
        m_pickerViewController = [[MyPickerViewController alloc] init];
        
    }
    m_pickerViewController.delegate = self;
    [m_pickerViewController setDataWithArrays:[Global cartypeList], nil];
    [m_pickerViewController show];
}
-(void)myPickerViewSelectedIndex:(NSInteger)selectedIndex inComponment:(NSInteger)componment
{
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (m_lastSelectedIndexPath == nil || ![m_lastSelectedIndexPath isEqual:indexPath])
    {
        return 35;
    }
    else
    {
        return 140;
    }
}
-(void)myPickerViewChanged:(NSArray *)allIndex
{
    NSInteger selectedIndex = ((NSNumber*)[allIndex objectAtIndex:0]).integerValue;
    m_cartypeIndex = selectedIndex;
    NSArray* list = [Global cartypeList];
    NSString* text = [list objectAtIndex:selectedIndex];
    NSString* info = [[Global carInfoList] objectAtIndex:selectedIndex];
    [cartypeBtn setTitle:text forState:UIControlStateNormal];
    [self.carinfoLabel setText:info];
    KRELEASE(m_lastSelectedIndexPath);
    [self reloadDataWithCartype:text];
}
-(void)dealloc
{
    [self viewDidUnload];
    KRELEASE(m_dataDic);
    KRELEASE(m_pickerViewController);
    KRELEASE(m_xml);
    KRELEASE(m_lastSelectedIndexPath);
    [super dealloc];
}
@end
